#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanXinyangPolicy(BaseTaxPolicySpider):
    name = 'henan_xinyang_rmzf_policy'
    
    province = '河南省'
    city = '信阳市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['信阳市淮滨县发展和改革委员会', "淮滨县", "A0915150102"],
            ['信阳市淮滨县工业和信息化局', "淮滨县", "A0915150131"],
            # ['信阳市淮滨县科学技术局', "淮滨县", ""],
            ['信阳市淮滨县人力资源和社会保障局', "淮滨县", "A0915150112"],
            ['信阳市淮滨县住房和城乡建设局', "淮滨县", "A0915150154"],
            ['信阳市淮滨县文化广电和旅游局', "淮滨县", "A0915150126"],
            ['信阳市淮滨县商务局', "淮滨县", "A0915150118"],
            # ['信阳市淮滨县投资促进局', "淮滨县", ""],
            ['信阳市淮滨县市场监督管理局', "淮滨县", "A0915150153"],
            ['信阳市淮滨县财政局', "淮滨县", "A0915150111"],
        ]:
            url = f"http://www.huaibin.gov.cn/cms/pub/xxgk/xxgklist.jsp?__go2pageNO=1&channelcode={url}&Theselect=&topic=&indexid=&__go2pageNum=1"
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//div[@class='xxgkbiaoge' or @class='article-list' or @class='bd']//td//a[(contains(@href, '.htm') or @title)]/ancestor::td[string-length(string(.))>=10] | "
            "//ul[contains(@class, 'ul ULLIST') or contains(@class, 'List') or contains(@class, 'list')]//li//a[@class or contains(@href, 'htm')]/ancestor::li[string-length(string(.))>=10]"
        )
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if not item['source_url'].endswith(".htm") and '.shtm' not in item['source_url']:
                continue
            # if 'relativeInfo' in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})

        if response.meta.get("is_next") is not False:
            pages = response.xpath(""".""").re_first(r'第1/(\d+)页')
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace("pageNO=1", f"pageNO={page_num}")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
            # else:
            #     next_url = response.xpath("//a[text()='下一页' or text()='下页']/@href").get()
            #     print("next_url", next_url)
            #     if next_url != response.url:
            #         yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布日期：') or contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_xinyang_rmzf_policy".split())
